package com.ewili.x.special.service.data.impl;

import com.ewili.framework.utils.DateUtils;
import com.ewili.framework.utils.ExceptionUtils;
import com.ewili.x.special.dao.inter.BaiduEventDao;
import com.ewili.x.special.service.data.inter.AsyncService;
import com.ewili.x.special.service.data.inter.BaiduEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class BaiduEventServiceImpl implements BaiduEventService {

    @Autowired
    private BaiduEventDao baiduEventDao;

    @Autowired
    private AsyncService asyncService;


    @Override
    public void baiduEventSpide() {
        try {
            List<Date> wholeDates = this.getWholeDates(DateUtils.parseDate("2013-01-01", DateUtils.yyyy_MM_dd));
            if (wholeDates.isEmpty()) {
                return;
            }
            this.spideHotStocks(wholeDates);
        } catch (ParseException e) {
            ExceptionUtils.propagate(e);
        }

    }

    /**
     * 获取热点股
     *
     * @param dates
     * @return
     */
    private void spideHotStocks(List<Date> dates) {
        if (dates.isEmpty()) {
            return;
        }
        for (Date date : dates) {
            if (baiduEventDao.existsByDate(date)) {
                continue;
            }
            String dateStr = DateUtils.format(date, DateUtils.yyyy_MM_dd);
            String url = "http://gupiao.baidu.com/concept/?searchdate=" + dateStr;
            asyncService.baiduEventUrlCode(url, dateStr);
        }
    }

    /**
     * 得到时间区间内所有日期
     *
     * @param startDate
     * @return
     */
    private List<Date> getWholeDates(Date startDate) {
        Date now = DateUtils.currentDate(DateUtils.yyyy_MM_dd);
        if (DateUtils.isSameDay(startDate, now)) {
            return Collections.emptyList();
        }
        startDate = DateUtils.addDays(startDate, 1);

        return getWholeDates(startDate, now);
    }

    /**
     * 得到时间区间内所有日期
     *
     * @param startDate
     * @param endDate
     * @return
     */
    private List<Date> getWholeDates(Date startDate, Date endDate) {
        List<Date> wholeDates = new ArrayList<>();
        wholeDates.add(startDate);
        Date date = DateUtils.addDays(startDate, 1);
        wholeDates.add(date);
        while (true) {
            date = DateUtils.addDays(date, 1);
            if (date.getTime() > endDate.getTime()) {
                break;
            }
            wholeDates.add(date);
        }
        return wholeDates;
    }
}
